package com.yunchang.springboot.scheduled.mwsreport;

import com.yunchang.springboot.base.BaseService;
import com.yunchang.springboot.mapper.mwsreport.MwsDataGetErrorRecordMapper;
import com.yunchang.springboot.mapper.shop.AreaMapper;
import com.yunchang.springboot.mapper.shop.ShopAreaMapper;
import com.yunchang.springboot.mapper.shop.ShopMapper;
import com.yunchang.springboot.models.Area;
import com.yunchang.springboot.models.Shop;
import com.yunchang.springboot.models.mwsreportbean.MwsDataGetErrorRecord;
import com.yunchang.springboot.utils.CryptoUtil;
import com.yunchang.springboot.utils.DateUtil;
import com.yunchang.springboot.utils.StringUtil;
import com.yunchang.springboot.utils.amazon.AmazonMwsUntil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 亚马逊api定时任务----------定时任务必须try-catch
 * <p>
 * 秒 ：范围:0－59
 * 分 ：范围:0－59
 * 时 ：范围:0-23
 * 天（月） ：范围:1-31,但要注意一些特别的月份2月份没有只能1-28，有些月份没有31
 * 月 ：用0-11 或用字符串 “JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV and DEC” 表示
 * 天（周）：用1-7表示（1 ＝ 星期日）或用字符口串“SUN, MON, TUE, WED, THU, FRI and SAT”表示
 * 年：范围:1970－2099
 * <p>
 * “/”：表示为“每”，如“0/10”表示每隔10分钟执行一次,“0”表示为从“0”分开始, “3/20”表示表示每隔20分钟执行一次
 * “?”：只用于月与周，表示不指定值
 * “L”：只用于月与周，5L用在月表示为每月的最后第五天天；1L用在周表示每周的最后一天；
 * “W”：:表示有效工作日(周一到周五),只能出现在day-of-month，系统将在离指定日期的最近的有效工作日触发事件。例如：在 DayofMonth使用5W，如果5日是星期六，则将在最近的工作日：星期五，即4日触发。如果5日是星期天，则在6日(周一)触发；如果5日在星期一到星期五中的一天，则就在5日触发。另外一点，W的最近寻找不会跨过月份
 * “#”：用于确定每个月第几个星期几，只能出现在DayofMonth域。例如在4#2，表示某月的第二个星期三。
 * “*” 代表整个时间段。
 * <p>
 * 注意：每个元素可以是一个值(如6),一个连续区间(9-12),一个间隔时间(8-18/4)(/表示每隔4小时),一个列表(1,3,5),通配符。由于"月份中的日期"和"星期中的日期"这两个元素互斥的,必须要对其中一个设置‘?’
 *
 * <p>
 * 官方解释：
 * 0 0 3 * * ?         每天 3 点执行
 * 0 5 3 * * ?         每天 3 点 5 分执行
 * 0 5 3 ? * *         每天 3 点 5 分执行
 * 0 5/10 3 * * ?      每天 3 点 5 分，15 分，25 分，35 分，45 分，55 分这几个点执行
 * 0 10 3 ? * 1        每周星期天的 3 点10 分执行，注：1 表示星期天
 * 0 10 3 ? * 1#3      每个月的第三个星期的星期天 执行，#号只能出现在星期的位置
 *
 * @author wanglongwei
 * @data 2019/7/15 16:27
 */


/**
 * @author 1
 */
@Component
@Configuration
@Service
@Slf4j
@EnableScheduling
public class ReportBase extends BaseService {
    @Autowired
    ShopAreaMapper shopAreaMapper;

    @Autowired
    ShopMapper shopMapper;

    @Autowired
    AreaMapper areaMapper;

    private MwsDataGetErrorRecordMapper mwsDataGetErrorRecordMapper;

    @Autowired
    public void setMwsDataGetErrorRecordMapper(MwsDataGetErrorRecordMapper mwsDataGetErrorRecordMapper) {
        this.mwsDataGetErrorRecordMapper = mwsDataGetErrorRecordMapper;
    }

    protected static Integer INSERT_MAX_NUM = 10000;

    /**
     * 使用订阅服务获取报告的任务名称
     */
//    protected final List<String> TASK_NAME_SUBSCRIPTIONS = Arrays.asList("管理亚马逊库存");

//    protected final List<String> TASK_NAME_SUBSCRIPTIONS = Arrays.asList( "库存调整", "库存仓储超量费","已接收库存", "每月库存记录", "月储存费用", "费用预览", "长期仓储费", "退货", "移除订单详情",
//            "移除货件详情", "已完成订单", "赔偿", "每日库存记录", "在售商品报告","预留库存", "所有订单", "管理亚马逊库存", "库龄", "盘库");

//    protected final List<String> TASK_NAME_SUBSCRIPTIONS = Arrays.asList( "库存调整","已接收库存", "每月库存记录", "月储存费用", "费用预览", "长期仓储费", "退货", "移除订单详情",
//            "移除货件详情", "已完成订单", "赔偿", "每日库存记录", "在售商品报告","预留库存", "所有订单", "管理亚马逊库存", "库龄", "盘库");

    protected final List<String> TASK_NAME_SUBSCRIPTIONS = Arrays.asList("库存调整", "库存仓储超量费", "已接收库存", "每月库存记录", "月储存费用", "费用预览", "长期仓储费", "退货", "移除订单详情",
            "移除货件详情", "已完成订单", "赔偿", "每日库存记录", "在售商品报告", "预留库存", "所有订单", "管理亚马逊库存", "库龄", "盘库");

//    protected final List<String> TASK_NAME_SUBSCRIPTIONS = Arrays.asList("移除货件详情");

    protected final List<String> TASK_NAME_SUBSCRIPTIONS_TEST = Arrays.asList("长期仓储费");

    /**
     * 每月获取报告的任务名称
     */
    protected final List<String> TASK_NAME_SUBSCRIPTIONS_EVERY_MONTH = Arrays.asList("每月库存记录", "月储存费用", "长期仓储费", "库存调整", "库存仓储超量费");

//    /**
//     * 需要获取历史数据的报告名称
//     */
//    protected final List<String> TASK_NAME_SUBSCRIPTIONS_TEST_HISTORY = Arrays.asList("所有订单","盘库", "已接收库存", "每月库存记录", "月储存费用", "长期仓储费", "退货", "移除订单详情", "移除货件详情", "已完成订单", "赔偿", "每日库存记录", "库存调整");

    /**
     * 需要获取历史数据的报告名称
     */
    protected final List<String> TASK_NAME_SUBSCRIPTIONS_TEST_HISTORY = Arrays.asList("所有订单","盘库", "已接收库存", "每月库存记录", "月储存费用", "长期仓储费", "退货", "移除订单详情", "移除货件详情", "已完成订单", "赔偿", "每日库存记录", "库存调整");
//    ,"盘库", "已接收库存", "每月库存记录", "月储存费用", "长期仓储费", "退货", "移除订单详情", "移除货件详情", "已完成订单", "赔偿", "每日库存记录", "库存调整"

//    /**
//     * 需要获取历史数据的报告名称
//     */
//    protected final List<String> TASK_NAME_SUBSCRIPTIONS_TEST_HISTORY = Arrays.asList("所有订单","盘库", "已接收库存", "每月库存记录", "月储存费用", "长期仓储费", "退货", "移除订单详情", "移除货件详情", "已完成订单", "赔偿", "每日库存记录", "库存调整", "库存仓储超量费");

    /**
     * 全部站点都下载的任务名称
     */
    protected final List<String> TASK_NAME_SUBSCRIPTIONS_ALL_AREA = Arrays.asList("payment", "预留库存", "管理亚马逊库存", "库龄", "在售商品报告");

    /**
     * North America region 北美地区
     */
    protected final List<String> NORTH_AMERICA_REGION = Arrays.asList("BR", "CA", "MX", "US");

    /**
     * Europe region 欧洲地区
     */
    protected final List<String> EUROPE_REGION = Arrays.asList("AE", "DE", "EG", "ES", "FR", "GB", "IN", "IT", "SA", "TR");

    /**
     * Far East region 远东地区
     */
    protected final List<String> FAR_EAST_REGION = Arrays.asList("SG", "AU", "JP");

    /**
     * 北美地区代表区域
     */
    protected final String NORTH_AMERICA_REGION_REPRESENTATIVE = "US";

    /**
     * 欧洲地区代表区域
     */
    protected final String EUROPE_REGION_REPRESENTATIVE = "DE";

    /**
     * 远东地区代表区域
     */
    protected final String FAR_EAST_REGION_REPRESENTATIVE = "JP";

    /**
     * 由于日本地区的表头和其他区域不同所以需要区分
     */
    protected final String ESPECIALLY_AREA = "JP";

    /**
     * 墨西哥区域代码
     * 因为墨西哥区域不支持订阅功能，需要单独处理
     */
    protected final String MX_AREA = "MX";

    /**
     * all order 枚举值
     */
    protected final String ALL_ORDER_ENUMERATION = "_GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_";

    /**
     * 盘库 枚举值
     */
    protected final String INVENTORY_ADJUSTMENTS = "_GET_FBA_FULFILLMENT_INVENTORY_ADJUSTMENTS_DATA_";

    /**
     * 已接收库存 枚举值
     */
    protected final String RECEIVED_INVENTORY = "_GET_FBA_FULFILLMENT_INVENTORY_RECEIPTS_DATA_";

    /**
     * 每月库存记录 枚举值
     */
    protected final String MONTHLY_INVENTORY_HISTORY = "_GET_FBA_FULFILLMENT_MONTHLY_INVENTORY_DATA_";

    /**
     * 月储存费用 枚举值
     */
    protected final String MONTHLY_STORAGE_FEES = "_GET_FBA_STORAGE_FEE_CHARGES_DATA_";

    /**
     * 费用预览 枚举值
     */
    protected final String FEE_PREVIEW = "_GET_FBA_ESTIMATED_FBA_FEES_TXT_DATA_";

    /**
     * 长期仓储费 枚举值
     */
    protected final String LONG_TERM_STORAGE_FEE_CHARGES = "_GET_FBA_FULFILLMENT_LONGTERM_STORAGE_FEE_CHARGES_DATA_";

    /**
     * 退货 枚举值
     */
    protected final String FBA_CUSTOMER_RETURNS = "_GET_FBA_FULFILLMENT_CUSTOMER_RETURNS_DATA_";

    /**
     * 移除订单详情 枚举值
     */
    protected final String REMOVAL_ORDER_DETAIL = "_GET_FBA_FULFILLMENT_REMOVAL_ORDER_DETAIL_DATA_";

    /**
     * 移除货件详情 枚举值
     */
    protected final String REMOVAL_SHIPMENT_DETAIL = "_GET_FBA_FULFILLMENT_REMOVAL_SHIPMENT_DETAIL_DATA_";

    /**
     * 已完成订单 枚举值
     */
    protected final String CUSTOMER_SHIPMENT_SALES = "_GET_FBA_FULFILLMENT_CUSTOMER_SHIPMENT_SALES_DATA_";

    /**
     * 赔偿 枚举值
     */
    protected final String REIMBURSEMENTS = "_GET_FBA_REIMBURSEMENTS_DATA_";

    /**
     * 每日库存记录 枚举值
     */
    protected final String DAILY_INVENTORY_HISTORY = "_GET_FBA_FULFILLMENT_CURRENT_INVENTORY_DATA_";

    /**
     * 库存调整 枚举值
     */
    protected final String INVENTORY_RECONCILIATION = "_GET_FBA_RECONCILIATION_REPORT_DATA_";

    /**
     * 库存仓储超量费 枚举值
     */
    protected final String INVENTORY_STORAGE_OVERAGE_FEES = "_GET_FBA_OVERAGE_FEE_CHARGES_DATA_";

    /**
     * 在售商品报告 枚举值
     */
    protected final String ACTIVE_LISTINGS_REPORT = "_GET_MERCHANT_LISTINGS_DATA_";

    /**
     * 管理亚马逊库存 枚举值
     */
    protected final String MANAGE_FBA_INVENTORY_ENUMERATION = "_GET_FBA_MYI_UNSUPPRESSED_INVENTORY_DATA_";

    /**
     * 预留库存 枚举值
     */
    protected final String RESERVED_INVENTORY_ENUMERATION = "_GET_RESERVED_INVENTORY_DATA_";


    /**
     * payment 枚举值
     */
    protected final String PAYMENT_ENUMERATION = "_GET_V2_SETTLEMENT_REPORT_DATA_FLAT_FILE_";

    /**
     * 库龄 枚举值
     */
    protected final String INVENTORY_AGE_ENUMERATION = "_GET_FBA_INVENTORY_AGED_DATA_";

    protected final String AWS_ACCESS_KEY_ID = "AKIATK7PTMS2SWBYRNAZ";

    protected final String AWS_SECRET_ACCESS_KEY = "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";


    /**
     * 数据库取出
     */
    protected final String COLUMN_SELLER_ID = "sellerId";
    protected final String COLUMN_MWS_AUTH_TOKEN = "mwsAuthToken";
    protected final String COLUMN_AWS_ACCESS_KEY_ID = "awsAccessKeyId";
    protected final String COLUMN_SECRET_KEY = "secretKey";
    protected final String COLUMN_SHOP_NAME = "shopName";
    protected final String COLUMN_SHOP_BRAND_NAME = "shopName";

    /**
     * 亚马逊api请求参数字段
     */
    protected final String PARAM_AWS_ACCESS_KEY_ID = "AWSAccessKeyId";
    protected final String PARAM_MWS_AUTH_TOKEN = "MWSAuthToken";
    protected final String PARAM_SELLER_ID = "SellerId";
    protected final String PARAM_MARKETPLACE_ID_LIST_ID = "MarketplaceIdList.Id.1";
    public final static String PUBLIC_PARAM_MARKETPLACE_ID_LIST_ID = "MarketplaceIdList.Id.1";
    protected final String PARAM_MARKETPLACE_ID = "MarketplaceId";
    protected final String PARAM_REPORT_REQUEST_ID_LIST_ID = "ReportRequestIdList.Id.1";


    /**
     * MarketplaceIdList 请求参数不在日本和中国使用。
     */
    protected final List<String> NOT_MARKETPLACE_ID_LIST_COUNTRY_CODE = Arrays.asList("JP", "CN");


    protected final String SPECIAL_SHOP_NAME = "SummerMae";

    protected final String SPECIAL_SHOP_NAME_TWO = "Luciphia JP";

    /**
     * MwsApi定时任务任务名称---详情参考更新频率思维导图
     */
    protected final String[] TASK_NAME = {"预留库存", "管理亚马逊库存", "all order", "库龄", "每日库存记录"
            , "FBA customer returns", "月度仓储费", "长期仓储费", "费用预览", "已接收库存", "每月库存记录", "盘库", "移除"
            , "移除货件详情", "已完成订单", "payment", "注册目的地", "测试目的地的可用性", "创建订阅"};

    /**
     * payment返回参数
     */
    protected static final String REPORT_ID = "ReportId";
    protected static final String PARAM_MAP = "paramMap";


    public ReportBase() {
    }

    /**
     * 定时任务开始之前校验检查shop和area信息
     *
     * @return 若返回null证明出错，正常返回shop和area的map
     */
    public Map<String, Object> beginScheduleTaskValidate(Shop shop) {
        String warnStr = "";
        Long SHOP_ID = shop.getId();
        Map<String, Object> shopMap = baseFindByClassAndId(Shop.class, SHOP_ID);
        if (null == shopMap) {
            log.warn(warnStr + "没有查询到shop信息，请检查shopId是否正确");
            return null;
        }
        String sellerId = String.valueOf(shopMap.get("seller_id"));
        if (StringUtil.isBlank(sellerId)) {
            log.warn(warnStr + "没有查询到sellerId信息，请检查shopId为" + SHOP_ID + "的sellerId信息是否正确");
            return null;
        }
        shopMap.put(COLUMN_SELLER_ID, CryptoUtil.decode(sellerId));
        String mwsAuthToken = String.valueOf(shopMap.get("mws_auth_token"));
        if (StringUtil.isBlank(mwsAuthToken)) {
            log.warn(warnStr + "没有查询到mwsAuthToken信息，请检查shopId为" + SHOP_ID + "的mwsAuthToken信息是否正确");
            return null;
        }
        shopMap.put(COLUMN_MWS_AUTH_TOKEN, CryptoUtil.decode(mwsAuthToken));
        String awsAccessKeyId = String.valueOf(shopMap.get("aws_access_key_id"));
        if (StringUtil.isBlank(awsAccessKeyId)) {
            log.warn(warnStr + "没有查询到awsAccessKeyId信息，请检查shopId为" + SHOP_ID + "的awsAccessKeyId信息是否正确");
            return null;
        }
        shopMap.put(COLUMN_AWS_ACCESS_KEY_ID, CryptoUtil.decode(awsAccessKeyId));
        String secretKey = String.valueOf(shopMap.get("secret_key"));
        if (StringUtil.isBlank(secretKey)) {
            log.warn(warnStr + "没有查询到secretKey信息，请检查shopId为" + SHOP_ID + "的secretKey信息是否正确");
            return null;
        }
        shopMap.put(COLUMN_SECRET_KEY, CryptoUtil.decode(secretKey));
        List<Area> areaListByShopId = shopAreaMapper.getAreaListByShopIdExcludeEU(SHOP_ID);
        for (Area area : areaListByShopId) {
            if (StringUtil.isBlank(area.getMwsEndPoint())) {
                log.warn(warnStr + "没有查询到区域名为" + area.getAreaName() + "区域亚马逊MWS 端点，请检查shopId为" + SHOP_ID + "的区域信息以及区域详情是否正确");
                return null;
            }
            if (StringUtil.isBlank(area.getMwsCountryCode())) {
                log.warn(warnStr + "没有查询到区域名为" + area.getAreaName() + "区域国家代码，请检查shopId为" + SHOP_ID + "的区域信息以及区域详情是否正确");
                return null;
            }
            if (StringUtil.isBlank(area.getMarketplaceId())) {
                log.warn(warnStr + "没有查询到区域名为" + area.getAreaName() + "区域MarketplaceId，请检查shopId为" + SHOP_ID + "的区域信息以及区域详情是否正确");
                return null;
            }
        }
        return new HashMap<String, Object>(2) {{
            put("shop", shopMap);
            put("area", areaListByShopId);
        }};
    }

    /**
     * 打印出错信息
     *
     * @param taskName
     * @param shopName
     * @param areaCountryCode
     * @param errorMsg
     */
    protected void logWarnErrorMsg(String taskName, String shopName, String areaCountryCode, StringBuffer errorMsg) {
        log.warn("↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓定时任务出错↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓");
        log.warn("×××××" + taskName + "×××定时任务出错×××" +
                "---店铺名称:" + shopName +
                "---区域国家代码:" + areaCountryCode +
                "×××××错误详情:" + errorMsg);
        log.warn("↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑定时任务出错↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑");
        MwsDataGetErrorRecord record = new MwsDataGetErrorRecord();
        record.setShop(shopName);
        record.setArea(areaCountryCode);
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date date = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = format.format(date);
        record.setDate(format1);
        //是否处理，0:未处理,1:已处理',
        record.setIsHandle(0);
        //类型:亚马逊MwsApi定时任务
        record.setName(taskName);
        record.setRemark("亚马逊MwsApi定时任务出错,任务名称:" + taskName
                + "出错的时间:" + format1
                + "错误详情:" + errorMsg);
        record.setCreateTime(DateUtil.getFutureDateTime(0));
        record.setType(1);
        mwsDataGetErrorRecordMapper.insertSelective(record);
    }

    /**
     * 打印出错信息 报告数据插入数据库时若发生错误记录该信息
     *
     * @param taskName
     * @param shopName
     * @param areaCountryCode
     * @param errorMsg
     */
    protected void logWarnErrorMsgByInsertData(String taskName, String shopName, String areaCountryCode, StringBuffer errorMsg) {
        log.warn("↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓定时任务出错↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓");
        log.warn("×××××" + taskName + "×××定时任务出错×××" +
                "---店铺名称:" + shopName +
                "---区域国家代码:" + areaCountryCode +
                "×××××错误详情:" + errorMsg);
        log.warn("↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑定时任务出错↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑");
        MwsDataGetErrorRecord record = new MwsDataGetErrorRecord();
        record.setShop(shopName);
        record.setArea(areaCountryCode);
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date date = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = format.format(date);
        record.setDate(format1);
        //是否处理，0:未处理,1:已处理',
        record.setIsHandle(0);
        //类型:亚马逊MwsApi定时任务
        record.setName(taskName);
        record.setRemark("亚马逊MwsApi定时任务出错,任务名称:" + taskName
                + "出错的时间:" + format1
                + "错误详情:" + errorMsg);
        record.setCreateTime(DateUtil.getFutureDateTime(0));
        record.setType(0);
        mwsDataGetErrorRecordMapper.insertSelective(record);
    }

    /**
     * 获取历史报告数据打印出错信息
     *
     * @param taskName
     * @param shopName
     * @param areaCountryCode
     * @param errorMsg
     */
    protected void logWarnHistoryReportDateErrorMsg(String taskName, String shopName, String areaCountryCode, StringBuffer errorMsg, String taskBeginTime, String taskEndTime) {
        log.warn("↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓定时任务出错↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓");
        log.warn("×××××" + taskName + "×××定时任务出错×××" +
                "---店铺名称:" + shopName +
                "---区域国家代码:" + areaCountryCode +
                "×××××错误详情:" + errorMsg);
        log.warn("↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑定时任务出错↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑");
        MwsDataGetErrorRecord record = new MwsDataGetErrorRecord();
        record.setShop(shopName);
        record.setArea(areaCountryCode);
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date date = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = format.format(date);
        record.setDate(format1);
        //是否处理，0:未处理,1:已处理',
        record.setIsHandle(0);
        //类型:亚马逊MwsApi定时任务
        record.setName(taskName);
        record.setRemark("亚马逊MwsApi定时任务出错,任务名称:" + taskName
                + "出错的时间:" + format1
                + "错误详情:" + errorMsg);
        record.setCreateTime(DateUtil.getFutureDateTime(0));
        record.setType(1);
        record.setTaskBeginTime(taskBeginTime);
        record.setTaskEndTime(taskEndTime);
        mwsDataGetErrorRecordMapper.insertSelective(record);
    }

    /**
     * 根据任务名称获取店铺及区域名
     *
     * @param taskName
     */
    public List<Map<Shop, Area>> getShopNameAndAreaByTaskName(String taskName) {
        List<Map<Shop, Area>> shopAndAreaMapList = new ArrayList<>();
        List<Shop> shopList = shopMapper.getAllList();
        for (Shop shop : shopList) {
            Map<Shop, Area> shopAndAreaMap = new ConcurrentHashMap<>();
            Long shopId = shop.getId();
            String sellerId = shop.getSellerId();
            if (StringUtil.isBlank(sellerId)) {
                log.warn("没有查询到sellerId信息，请检查shopId为" + shopId + "的sellerId信息是否正确");
            }
            String mwsAuthToken = shop.getMwsAuthToken();
            if (StringUtil.isBlank(mwsAuthToken)) {
                log.warn("没有查询到mwsAuthToken信息，请检查shopId为" + shopId + "的mwsAuthToken信息是否正确");
            }
            String awsAccessKeyId = shop.getAwsAccessKeyId();
            if (StringUtil.isBlank(awsAccessKeyId)) {
                log.warn("没有查询到awsAccessKeyId信息，请检查shopId为" + shopId + "的awsAccessKeyId信息是否正确");
            }
            String secretKey = shop.getSecretKey();
            if (StringUtil.isBlank(secretKey)) {
                log.warn("没有查询到secretKey信息，请检查shopId为" + shopId + "的secretKey信息是否正确");
            }
            List<Area> areaListByShopId = shopAreaMapper.getAreaListByShopIdExcludeEU(shopId);
            for (Area area : areaListByShopId) {
                if (StringUtil.isBlank(area.getMwsEndPoint())) {
                    log.warn("没有查询到区域名为" + area.getAreaName() + "区域亚马逊MWS 端点，请检查shopId为" + shopId + "的区域信息以及区域详情是否正确");
                }
                if (StringUtil.isBlank(area.getMwsCountryCode())) {
                    log.warn("没有查询到区域名为" + area.getAreaName() + "区域国家代码，请检查shopId为" + shopId + "的区域信息以及区域详情是否正确");
                }
                if (StringUtil.isBlank(area.getMarketplaceId())) {
                    log.warn("没有查询到区域名为" + area.getAreaName() + "区域MarketplaceId，请检查shopId为" + shopId + "的区域信息以及区域详情是否正确");
                }
            }
            shop.setSecretKey(CryptoUtil.decode(shop.getSecretKey()));
            shop.setAwsAccessKeyId(CryptoUtil.decode(shop.getAwsAccessKeyId()));
            shop.setMwsAuthToken(CryptoUtil.decode(shop.getMwsAuthToken()));
            shop.setSellerId(CryptoUtil.decode(shop.getSellerId()));
            // 根据任务名判断是否需要对区域进行处理
            if (!TASK_NAME_SUBSCRIPTIONS_ALL_AREA.contains(taskName)) {
                List<String> allMWSCountryCodeList = new ArrayList<>();
                for (Area area : areaListByShopId) {
                    String MWSCountryCode = area.getMwsCountryCode();
                    if (NORTH_AMERICA_REGION.contains(MWSCountryCode)) {
                        allMWSCountryCodeList.add(NORTH_AMERICA_REGION_REPRESENTATIVE);
                    } else if (EUROPE_REGION.contains(MWSCountryCode)) {
                        allMWSCountryCodeList.add(EUROPE_REGION_REPRESENTATIVE);
                    } else if (FAR_EAST_REGION.contains(MWSCountryCode)) {
                        allMWSCountryCodeList.add(FAR_EAST_REGION_REPRESENTATIVE);
                    } else {
                        log.error("出现未知区域：" + MWSCountryCode);
                    }
                }
                // 对重复的区域进行去重
                LinkedList<String> onlyMWSCountryCodeList = new LinkedList<>();
                Iterator<String> it = allMWSCountryCodeList.iterator();
                while (it.hasNext()) {
                    String str = it.next();
                    if (!onlyMWSCountryCodeList.contains(str)) {
                        onlyMWSCountryCodeList.add(str);
                    }
                }
                // 将mwsCountryCode转换为area对象
                for (String mwsCountryCode : onlyMWSCountryCodeList) {
                    Area area = areaMapper.getAreaByMWSCountryCode(mwsCountryCode);
                    shopAndAreaMap.put(shop, area);
                    shopAndAreaMapList.add(shopAndAreaMap);
                }
            } else {
                for (Area area : areaListByShopId) {
                    shopAndAreaMapList.add(new HashMap<Shop, Area>() {{
                        put(shop, area);
                    }});
                }
            }
        }
        return shopAndAreaMapList;
    }

    /**
     * 根据任务名获取日常任务获取报告的开始时间和结束时间
     *
     * @param taskName
     * @return 开始时间的key值为startTime 结束时间的key值为endTime
     */
    public Map<String, String> getReportStartAndEndTimeByTaskName(String taskName) {
        if (StringUtils.isEmpty(taskName)) {
            log.warn("参数taskName为空，taskName: " + taskName);
            return null;
        }
        String taskStartTimes;
        String taskEndTimes;
        switch (taskName) {
            case "所有订单":
                taskStartTimes = AmazonMwsUntil.urlEncode(DateUtil.timeToISO8601ZeroTimeZone((DateUtil.getFutureDateDay(-30))));
                taskEndTimes = AmazonMwsUntil.urlEncode(DateUtil.timeToISO8601ZeroTimeZone((DateUtil.getFutureDateDayLastTime(0))));
                return new HashMap<String, String>(2) {{
                    put("startTime", taskStartTimes);
                    put("endTime", taskEndTimes);
                }};
            case "盘库":
            case "已接收库存":
            case "退货":
            case "移除订单详情":
            case "移除货件详情":
            case "已完成订单":
            case "赔偿":
            case "每日库存记录":
                taskStartTimes = AmazonMwsUntil.urlEncode(DateUtil.timeToISO8601ZeroTimeZone((DateUtil.getFutureDateDay(-2))));
                taskEndTimes = AmazonMwsUntil.urlEncode(DateUtil.timeToISO8601ZeroTimeZone((DateUtil.getFutureDateDayLastTime(-2))));
                return new HashMap<String, String>(2) {{
                    put("startTime", taskStartTimes);
                    put("endTime", taskEndTimes);
                }};
            case "每月库存记录":
            case "月储存费用":
            case "长期仓储费":
            case "库存调整":
            case "库存仓储超量费":
                taskStartTimes = AmazonMwsUntil.urlEncode(DateUtil.timeToISO8601ZeroTimeZone((DateUtil.getMonthFirstDayByDate(new Date(), -1))));
                taskEndTimes = AmazonMwsUntil.urlEncode(DateUtil.timeToISO8601ZeroTimeZone((DateUtil.getMonthFirstDayByDate(new Date(), -1))));
                return new HashMap<String, String>(2) {{
                    put("startTime", taskStartTimes);
                    put("endTime", taskEndTimes);
                }};
        }
        return null;
    }
}
